package com.mousycoder.redis.service;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.mousycoder.redis.domain.SysUser;
import com.mousycoder.redis.domain.SysUserExample;
import com.mousycoder.redis.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * TODO
 *
 * @author mousycoder
 * @version 1.0
 * @date 2022/4/25 10:03 AM
 */
@Service
public class BloomFilterService {


    @Resource
    private SysUserMapper sysUserMapper;

    private BloomFilter<Integer> bf;


    @PostConstruct
    public void initBloomFilter(){
        SysUserExample sysUserExample = new SysUserExample();
        List<SysUser> sysUserList = sysUserMapper.selectByExample(sysUserExample);
        if (CollectionUtils.isEmpty(sysUserList)){
            return;
        }

        bf = BloomFilter.create(Funnels.integerFunnel(),sysUserList.size());
        for (SysUser sysUser:sysUserList){
            bf.put(sysUser.getId());
        }
    }

    public boolean userIdExists(int id){
        return bf.mightContain(id);
    }

}
